package com.demo.eshop.pdetail.service.product.Impl;

import com.alibaba.fastjson.JSON;
import com.demo.eshop.pdetail.constants.RedisKeys;
import com.demo.eshop.pdetail.dao.RedisDao;
import com.demo.eshop.pdetail.entity.ProductInventory;
import com.demo.eshop.pdetail.mapper.ProductInventoryMapper;
import com.demo.eshop.pdetail.service.product.ProductInventoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @author: e20160504
 * @date: 2018/10/29
 * @desc
 */

@Service
public class ProductInventoryServiceImpl implements ProductInventoryService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ProductInventoryMapper productInventoryMapper;
    @Resource
    private RedisDao redisDao;

    @Override
    public void updateProductInventory(ProductInventory productInventory) {
        productInventoryMapper.updateProductInventory(productInventory);
        logger.info("=======已更新数据库中的库存，商品id = {}, 更新商品库存为 = {}",productInventory.getProductId(),productInventory.getInventoryCnt());
    }

    @Override
    public void removeProductInventoryCache(ProductInventory productInventory){
        String key = "product:inventory:" + productInventory.getProductId();
        redisDao.del(key);
        logger.info("=======已删除redis中的缓存，key = {} ",key);
    }

    @Override
    public ProductInventory findProductInventory(Integer productId) {
        return productInventoryMapper.selectByPrimaryKey(new ProductInventory(productId,null));
    }

    @Override
    public void setProductInventoryCache(ProductInventory productInventory) {
        String key = RedisKeys.PROD_INVENTORY_REDIS_KEY + productInventory.getProductId();
        redisDao.set(key, JSON.toJSONString(productInventory.getInventoryCnt()));
        logger.info("===已更新商品库存的缓存，key = {}",key);
    }

    @Override
    public ProductInventory getProductInventoryCache(Integer productId) {
        String s = redisDao.get(RedisKeys.PROD_INVENTORY_REDIS_KEY + productId);
        Long inventory = 0L;
        if(!StringUtils.isEmpty(s)){
            inventory = Long.valueOf(s);
        }else{
            return null;
        }
        return new ProductInventory(productId,inventory.intValue());
    }


}
